import React from 'react'
import { browserHistory,hashHistory } from 'react-router'

import Api from '../router/Api'

import TopBar from '../components/TopBar'
import Footer from '../components/Footer'

import '../public/css/common.css'
import '../public/css/login.scss'

import imgTitlt from '../public/img/img_title.png'
import imgSecondTitle from '../public/img/img_second_title.png'
import Requestsign from '../public/js/requestSign'

class Login extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            username:"",
            code:"",
            errmsg : "",
            btnVal:"获取验证码",
            second:60,
            disabled:false,
            imgShow:false,
            imgCode:"",
            imgSize:""
        }
    }
    handleChangeUsername(e){
        let uName = e.target.value;
        if(uName.length < 11 || uName === ''){
            this.setState({
                errmsg:"请输入您的账号"
            })
        }else{
            if(!(/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(uName))){
                this.setState({
                    errmsg:"请输入正确的手机号",
                    username:uName
                })
            }else{
                this.setState({
                    errmsg:"",
                    username:uName
                })
            }
        }
    }
    handleGetCode(e){
        e.preventDefault();
        const _this = this;
       Api.getCode({phone:this.state.username}).then(function (res) {
            if(res.data.success){
                _this.timerId = setInterval(() => _this.tick(),1000);
            }else{
                _this.setState({
                    errmsg:res.data.cause
                })
            }
        }).catch(function (error) {
            console.log(error);
        });
    }
    tick(){
        this.setState((preSecond)=>({
            second:preSecond.second - 1,
            btnVal:`${preSecond.second - 1}s`,
            disabled:true
        }),()=>{
          if(this.state.second === 0){
              clearInterval(this.timerId);
              this.setState({
                  second:5,
                  btnVal:`重新发送`,
                    disabled:false
              })
          }
        })
    }
    handleChangeCode(e){
        let uCode = e.target.value;
        if(uCode.length < 6 || uCode ==="" || uCode==="undefined"){
            this.setState({
                errmsg:"请输入您的短信验证码"
            })
        }else {
            if(!(/^\d{6}$/.test(uCode))){
                this.setState({
                    errmsg:"请输入正确的短信验证码"
                })
            }else{
                this.setState({
                    errmsg:"",
                    code:uCode
                })
            }
        }
    }
    handleChangeImgCode(e){
        e.preventDefault();
        let uImgCode = e.target.value;
        if(uImgCode.length < 4 || uImgCode === '' || uImgCode === 'undefined'){
            this.setState({
                errmsg:"请输入您的图形验证码"
            })
        }else{
            this.setState({
                errmsg:"",
                imgCode:uImgCode
            })
        }
    }
    handleClickImg(){
        console.log("ssss");
        const _this = this;
        Api.getImgCode().then(function (res) {
            var buff = new Buffer(res.data, 'binary').toString('base64');
            _this.setState({
                imgSize:`data:image/jpg;base64,${buff}`
            });
        })
    }
    handleSubmit(e){
        e.preventDefault();
        if(this.state.imgShow){
            if(this.state.imgCode === '' && this.state.imgCode === 'undefined'){
                this.setState({
                    errmsg:"请输入图形验证码"
                });
                return false
            }
        }
        if(this.state.username !== '' && this.state.code !== ""){
            const _this = this;
            Api.login({
                phone:this.state.username,
                smsCode:this.state.code,
                captchaCode:this.state.imgCode
            }).then(function (res) {
                if(res.data.code === 1102){
                    Api.getImgCode().then(function (res) {
                        var buff = new Buffer(res.data, 'binary').toString('base64');
                        _this.setState({
                            imgShow:true,
                            imgSize:`data:image/jpg;base64,${buff}`
                        });
                    })
                }else if(res.data.code === 200){
                    sessionStorage.setItem('token',res.data.data.token);
                    if(res.data.data.isActivation === 0){
                        sessionStorage.setItem('isActivation',0);
                        browserHistory.push('/activation');
                    }else{
                        sessionStorage.setItem('isActivation',1);
                        browserHistory.push('/');
                    }

                }else{
                    Api.getImgCode().then(function (res) {
                        var buff = new Buffer(res.data, 'binary').toString('base64');
                        _this.setState({
                            errmsg:res.data.cause,
                            imgShow:true,
                            imgSize:`data:image/jpg;base64,${buff}`
                        });
                    })
                }
            }).catch(function (err) {
                console.log(err);
            });
        }else{
            this.setState({
                errmsg:"您的登录信息不完整"
            })
        }
    }
    render(){
        return(
            <div>
                <TopBar/>
                <div className="login">
                    <img src={imgTitlt} alt=""/>
                    <img src={imgSecondTitle} alt=""/>
                    <form action="">
                        <div className="tel">
                            <input type="tel" placeholder="手机号" onChange={this.handleChangeUsername.bind(this)} maxLength={11}/>
                        </div>
                        <div className="code">
                            <input type="tel" placeholder="短信验证码" maxLength={6} onChange={this.handleChangeCode.bind(this)}/><button onClick={this.handleGetCode.bind(this)} disabled={this.state.disabled ? "disabled":""}>{this.state.btnVal}</button>
                        </div>
                        <div className={this.state.imgShow ? "imgcode" : "imgcode hide"}>
                            <input type="text" placeholder="请输入图形验证码" maxLength={4}/><img src={this.state.imgSize} alt="" onClick={this.handleClickImg.bind(this)}/>
                        </div>
                        <div className="erm">
                            {this.state.errmsg}
                        </div>
                        <div className="submit" onClick={this.handleSubmit.bind(this)}>登录</div>
                    </form>
                </div>
                <Footer/>
            </div>
        )
    }
}

export default Login